import cv2 as cv
import matplotlib.pyplot as plt

o = cv.imread(r"D:\AI\opencv\sources\samples\data\pic6.png")
#cv.imshow("source image",o)
#print(o)
#print(o.ravel())
#plt.hist(o.ravel(), 256)
#plt.show()
#直方图
#h =cv.calcHist([o],[0],None,[256],[0,255])
#threshold是设定的阈值
#maxval是当灰度值大于（或小于）阈值时将该灰度值赋成的值
#type规定的是当前二值化的方式

def image_hist(image):
    hist = cv.calcHist([image], [0], None, [256], [0, 255])
    plt.subplot(2, 2, 2), plt.title("source_hist")
    plt.plot(hist, color="black")
    plt.xlim([0, 256])

###大津算法
def Otsu_demo(image):
    ret,Otsu = cv.threshold(image, 0, 0xff, cv.THRESH_OTSU)
    plt.subplot(2, 2, 3), plt.title("Otsu")
    plt.imshow(Otsu)
    hist = cv.calcHist([Otsu], [0], None, [256], [0, 255])
    plt.subplot(2, 2, 4), plt.title("Otsu_hist")
    plt.plot(hist, color="r")
    plt.xlim([0, 255])


image = cv.cvtColor(o, cv.COLOR_BGR2GRAY)
plt.figure(figsize=(15, 15))
plt.subplot(2, 2, 1), plt.title("source")
plt.imshow(image, cmap="gray"), plt.axis("off")
image_hist(image)
Otsu_demo(image)
plt.show()



cv.waitKey()
cv.destroyAllWindows()


